package com.nescafe.nescafepromo.command.admin;

import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.QueryResultList;
import com.nescafe.nescafepromo.command.Command;
import com.nescafe.nescafepromo.command.CommandException;
import com.nescafe.nescafepromo.entity.EntityType;
import com.nescafe.nescafepromo.entity.Purchase;
import com.nescafe.nescafepromo.model.NPRequest;
import com.nescafe.nescafepromo.model.NPResponse;

public class SearchPurchases implements Command {

	@Override
	public NPResponse execute(NPRequest req) throws CommandException {
		NPResponse res = null;
		try {

			int pageSize = 15;
			long from = Long.parseLong(req.getParam("from"));
			long to = Long.parseLong(req.getParam("to"));
			int branch = Integer.parseInt(req.getParam("branch"));
			String email = req.getParam("email");

			Query q = new Query(EntityType.PURCHASE.getKind());
			FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);

			if (branch > 0) {
				q.addFilter("branch", FilterOperator.EQUAL, branch);
			}
			if (email != null && !email.isEmpty()) {
				q.addFilter("email", FilterOperator.EQUAL, email);
			} else {
				String cursor = req.getParam("cursor");
				if (cursor != null) {
					fetchOptions.startCursor(Cursor.fromWebSafeString(cursor));
				}
			}

			q.addFilter(Purchase.RECEIPT_DATE_FIELD, FilterOperator.GREATER_THAN_OR_EQUAL, from);
			q.addFilter(Purchase.RECEIPT_DATE_FIELD, FilterOperator.LESS_THAN_OR_EQUAL, to);
			q.addSort(Purchase.RECEIPT_DATE_FIELD, SortDirection.ASCENDING);

			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			PreparedQuery pq = ds.prepare(q);
			QueryResultList<Entity> queryResultList = pq.asQueryResultList(fetchOptions);
			res = new NPResponse(queryResultList);
			res.setCursor(queryResultList.getCursor());
		} catch (Exception e) {
			throw new CommandException(e.getMessage());
		}
		return res;
	}
}
